package com.justnow.offer;

/**
 * @author justnow
 * Created on 2020-09-17
 * Description
 */
public class Solution53 {
    public boolean exist(char[][] board, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                char[] path = new char[word.length()];
                if (dfs(i, j, chars, board, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(int i, int j, char[] chars, char[][] board, int k) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != chars[k]) {
            return false;
        }
        if (k == chars.length - 1) return true;
        char tmp = board[i][j];
        board[i][j] = '/';
        boolean res = dfs(i-1, j, chars, board, k + 1) || dfs(i + 1, j, chars, board, k + 1)
                || dfs(i, j - 1, chars, board, k + 1) || dfs(i, j + 1, chars, board, k + 1);
        board[i][j] = tmp;
        return res;
    }
}
